/*
 * Libre Boot, an automated boot for removing spammers off IRC channels
 * Copyright (C) 2018 Fedja Beader fedja@protonmail.ch
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/* TODO ideas:
 * - ban (and unban after a set time)
 *   - save bans to a file
 * - privmsg channel operators in case we are not opped
 * - chanserv op if we are not opped but are +o on access list
 */
#include <znc/Chan.h>
#include <znc/IRCNetwork.h>

class CLibreBootMod : public CModule {
public:
	MODCONSTRUCTOR(CLibreBootMod) {
		m_thresh_nicks = 3;

		AddHelpCommand();
	}

	~CLibreBootMod() override {}

	void ProcessMessage(const CChan& channel, const CNick& nick, const CString& text) {
		// 1. Are we OP in channel?
		if (! channel.HasPerm(CChan::Op))
			return;
		// 2. Does text include at least m_thresh_nicks mentions?
		SCString tokens;
		text.Split(" ", tokens, false, "", "", false, true);
		unsigned hits = 0;

		CString tokenised;
		for (const CString& token : tokens) {
			if (nullptr != channel.FindNick(token))
				hits++;
			tokenised + '"' + token + "\", ";
		}
		CString sHits (hits);
		if (text.size() > 150)
			PutModule("Hits " + sHits + " for " + tokenised);
		// 3. ...
		if (hits < m_thresh_nicks)
			return;
		// 4) Profit! Err... I mean kickban
		PutModule("Kickbanned " + nick.GetNickMask() + " for " + sHits + " mentions in \""
		  + text + "\" i.e. [" + tokenised + "]");
		//MODE <channel> <flags> [<args>]
		PutIRC ("MODE " + channel.GetName() + " +q *!*@" + nick.GetHost());
		//KICK <channel> <client> [<message>]
		PutIRC("KICK " + channel.GetName() + " " + nick.GetNick() + " automatic kick for mass-highlight spam.");
		//PRIVMSG <msgtarget> <message>
		//Sends <message> to <msgtarget>, which is usually a user or channel.[31] Defined in RFC 1459
	}
	EModRet OnChanMsg(CNick& nick, CChan& channel, CString& text) override {
		ProcessMessage(channel, nick, text);
		return CONTINUE;
	}

	EModRet OnChanAction(CNick& nick, CChan& channel, CString& text) override {
		ProcessMessage(channel, nick, text);
		return CONTINUE;
	}

private:
	unsigned m_thresh_nicks;
};

template <>
void TModInfo<CLibreBootMod>(CModInfo& Info) {
	Info.SetHasArgs(false);
}

USERMODULEDEFS(CLibreBootMod, "The Libre Boot boots spammers from controlled channels")
